<template>
	<div class="user-profile">
		<el-row>
			<el-col :span="6">
				<el-card shadow="always">
					<div slot="header" class="clearfix title">
						<span>个人信息</span>
					</div>
					<div class="avatar-box">
						<el-avatar :size="130" :src="showUser.avatar" class="avatar"></el-avatar>
						<div class="shape" @click="openUpdateAvatarDialog('user')">+</div>
					</div>
					<el-descriptions :column="1" border>
						<el-descriptions-item label="用户名称">{{
							showUser.username
						}}</el-descriptions-item>
						<el-descriptions-item label="用户昵称">{{
							showUser.nickname
						}}</el-descriptions-item>
						<el-descriptions-item label="手机号码">{{
							showUser.phone
						}}</el-descriptions-item>
						<el-descriptions-item label="用户邮箱">{{
							showUser.email
						}}</el-descriptions-item>
						<el-descriptions-item label="创建日期">
							{{ showUser.createTime }}
						</el-descriptions-item>
					</el-descriptions>
				</el-card>
			</el-col>

			<el-col :span="17" style="margin: 0 0 0 20px; font-weight: 700"
				><el-card shadow="always">
					<div slot="header" class="clearfix title">
						<span>{{ activeTab }}</span>
					</div>
					<el-tabs v-model="activeTab">
						<el-tab-pane label="基本资料" name="基本资料">
							<el-form
								ref="baseUserForm"
								label-position="left"
								label-width="80px"
								:model="baseUserForm"
								:rules="baseUserRules"
							>
								<el-form-item label="用户昵称" prop="nickname" required>
									<el-input v-model="baseUserForm.nickname"></el-input>
								</el-form-item>
								<el-form-item label="手机号码" prop="phone" required>
									<el-input v-model="baseUserForm.phone"></el-input>
								</el-form-item>
								<el-form-item label="邮箱" prop="email" required>
									<el-input v-model="baseUserForm.email"></el-input>
								</el-form-item>
								<el-form-item label="性别" prop="sex">
									<el-radio-group v-model="baseUserForm.sex">
										<el-radio label="0">男</el-radio>
										<el-radio label="1">女</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item>
									<el-button type="primary" @click="submitBaseUserForm"
										>保存</el-button
									>
									<el-button type="danger" @click="closeUserProfile"
										>关闭</el-button
									>
								</el-form-item>
							</el-form>
						</el-tab-pane>

						<el-tab-pane label="修改密码" name="修改密码">
							<el-form
								ref="passForm"
								label-position="left"
								label-width="80px"
								:model="passForm"
								:rules="passRules"
							>
								<el-form-item label="旧密码" prop="oldPass" required>
									<el-input v-model="passForm.oldPass"></el-input>
								</el-form-item>
								<el-form-item label="新密码" prop="newPass" required>
									<el-input v-model="passForm.newPass"></el-input>
								</el-form-item>
								<el-form-item label="确认密码" prop="confirmPass" required>
									<el-input v-model="passForm.confirmPass"></el-input>
								</el-form-item>
								<el-form-item>
									<el-button type="primary" @click="submitPassForm"
										>保存</el-button
									>
									<el-button type="danger" @click="closeUserProfile"
										>关闭</el-button
									>
								</el-form-item>
							</el-form>
						</el-tab-pane>

						<el-dialog
							title="修改头像"
							:visible.sync="updateAvatarDialogVisible"
							width="30%"
							style="min-width: 500px"
						>
							<el-row type="flex" justify="center">
								<el-col :span="12">
									<Cropper
										ref="avatarCropper"
										refCom="avatarCropper"
										:fixedBox="true"
										:img="cropper.avatar"
										@real-time="realTime"
										style="width: 100%; height: 200px"
									>
									</Cropper>
								</el-col>
								<el-col
									:span="10"
									:push="1"
									style="
										display: flex;
										justify-content: center;
										align-items: center;
									"
								>
									<div
										class="preview-box"
										:style="previewStyle"
										style="
											overflow: hidden;
											float: left;
											border-radius: 50%;
											border: 1px solid;
										"
									>
										<div class="preview" :style="previews.div">
											<img :src="previews.url" :style="previews.img" />
										</div>
									</div>
								</el-col>
							</el-row>
							<el-row slot="footer">
								<el-col :span="14" style="display: flex">
									<el-button>
										<el-upload
											:auto-upload="false"
											action="/avatar/upload"
											:on-change="beforeAvatarUpload"
											:show-file-list="false"
										>
											<i class="el-icon-upload"></i
										></el-upload>
									</el-button>
									<el-button @click="updateScale(1)">+</el-button>
									<el-button @click="updateScale(-1)">-</el-button>
									<el-button @click="rotateLeft">
										<img
											src="@/static/imgs/home/向左转.png"
											alt="向左转"
											height="13"
										/>
									</el-button>
									<el-button @click="rotateRight">
										<img
											src="@/static/imgs/home/向右转.png"
											alt="向右转"
											height="13"
										/>
									</el-button>
								</el-col>
								<el-col :span="10">
									<el-button type="primary" @click="submitNewAvatar">
										确 定
									</el-button>
								</el-col>
							</el-row>
						</el-dialog>
					</el-tabs>
				</el-card>
			</el-col>
		</el-row>
		<el-row style="padding: 10px">
			<el-col>
				<el-card shadow="always" style="padding: 10px">
					<div slot="header" class="clearfix title">
						商家信息
						<el-button type="primary" @click="openShop" v-if="!showShop.shopAvatar"
							>开通商家信息</el-button
						>
						<el-button type="success" @click="updateShop" v-if="showShop.shopAvatar"
							>修改商家信息</el-button
						>
					</div>
					<el-col v-if="showShop.shopAvatar">
						<div class="avatar-box">
							<el-avatar
								:size="130"
								:src="showShop.shopAvatar"
								class="avatar"
							></el-avatar>
							<div class="shape" @click="openUpdateAvatarDialog('shop')">+</div>
						</div>
						<el-descriptions border>
							<el-descriptions-item label="店铺名称">{{
								showShop.shopName
							}}</el-descriptions-item>
							<el-descriptions-item label="总评分">{{
								showShop.totalScore
							}}</el-descriptions-item>
							<el-descriptions-item label="评分人数">{{
								showShop.scoreNum
							}}</el-descriptions-item>
							<el-descriptions-item label="购买人数">{{
								showShop.buyNum
							}}</el-descriptions-item>
							<el-descriptions-item label="关注人数">{{
								showShop.followNum
							}}</el-descriptions-item>
							<el-descriptions-item label="开通时间">{{
								showShop.createTime
							}}</el-descriptions-item>
						</el-descriptions>
					</el-col>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script>
import { updatePass, getUserInfo, updateUser, updateAvatar } from "@/api/user-profile"
import { getOneShop, openShop, updateShop, updateShopAvatar } from "@/api/system/shop"
import { uploadAvatar } from "@/api/upload"
import { TagCurMenu } from "@/utils/index.js"
import Cropper from "@/components/cropper/Index.vue"
import { baseUserRules, passRules } from "@/utils/rules/user"
import UserUtil from "@/utils/user-util"
export default {
	name: "FrontAdminUserPersonal",
	components: {
		Cropper,
	},
	data() {
		return {
			type: "",
			updateAvatarDialogVisible: false,
			activeTab: "基本资料",
			showUser: {
				username: "",
				password: "",
				role: 0,
				phone: "",
				email: "",
				avatar: require("@/static/imgs/home/收缩菜单.png"),
				createTime: "",
				nickname: "",
				sex: "",
			},
			showShop: {
				shopAvatar: "",
				shopName: "",
				crateTime: "",
				totalScore: "",
				scoreNum: "",
				buyCount: "",
				createTime: "",
				userId: "",
			},
			baseUserForm: {
				nickname: "",
				phone: "",
				email: "",
				sex: "",
			},

			cropper: {
				avatar: null,
			},
			passForm: {
				oldPass: "",
				newPass: "",
				confirmPass: "",
			},

			previews: {},
			previewStyle: {},
			zooms: [1],
		}
	},
	computed: {
		baseUserRules,
		passRules() {
			let checkNewPass = (rule, value, callback) => {
				if (!value) {
					return callback(new Error("新密码不能为空"))
				} else if (!UserUtil.verifyPassword(value)) {
					return callback(new Error("新密码格式不对"))
				} else if (value == this.passForm.oldPass) {
					return callback(new Error("新密码和旧密码不能一致"))
				} else {
					callback()
				}
			}

			let checkConfirmPass = (rule, value, callback) => {
				if (!value) {
					return callback(new Error("确认密码不能为空"))
				} else if (value != this.passForm.newPass) {
					return callback(new Error("两次输入的密码不一致"))
				} else {
					callback()
				}
			}

			return {
				confirmPass: [{ validator: checkConfirmPass, trigger: "blur" }],
				newPass: [{ validator: checkNewPass, trigger: "blur" }],
				...passRules(),
			}
		},
	},
	mounted() {
		this.get()
	},
	methods: {
		async get() {
			let res = await getUserInfo()
			if (res.code == 200 && res.data) {
				this.showUser = { ...res.data.user }
				this.baseUserForm = { ...res.data.user }
			}
			let res1 = await getOneShop()
			if (res1.code == 200 && res1.data) {
				this.showShop = res1.data
			}
		},

		openUpdateAvatarDialog(type) {
			if (type == "user") {
				this.cropper.avatar = this.showUser.avatar
			} else {
				this.cropper.avatar = this.showShop.shopAvatar
			}
			this.type = type
			this.updateAvatarDialogVisible = true
		},

		closeUserProfile() {
			this.deleteTagAndUpdateCurMenu(this, { path: "/user/profile", label: "个人中心" })
		},

		submitNewAvatar() {
			this.$refs.avatarCropper.getCropBlob(async (blobUrl) => {
				let file = new File([blobUrl], "avatar.png")
				let data = new FormData()
				data.append("file", file)
				if (this.type == "user") {
					this.submitUserAvatar(data)
				} else {
					this.submitShopAvatar(data)
				}
			})
		},
		async submitShopAvatar(data) {
			let res1 = await uploadAvatar(data)
			if (res1.code == 200) {
				this.showShop.shopAvatar = res1.data.imgUrls[0]
				let res = await updateShopAvatar(this.showShop)
				if (res.code == 200) {
					this.get()
					this.updateAvatarDialogVisible = false
				}
			}
		},
		async submitUserAvatar(data) {
			let res1 = await uploadAvatar(data)
			if (res1.code == 200) {
				this.showUser.avatar = res1.data.imgUrls[0]
				let res = await updateAvatar(this.showUser)
				if (res.code == 200) {
					this.get()
					this.updateAvatarDialogVisible = false
				}
			}
		},
		openShop() {
			this.submitShop("开通商家服务", async ({ value }) => {
				let res = await openShop({
					shopName: value,
				})
				if (res.code == 200) {
					this.sucMes(this, "开通商家服务成功!")
					this.get()
				}
			})
		},
		updateShop() {
			this.submitShop("修改商家信息", async ({ value }) => {
				let res = await updateShop({
					shopName: value,
					userId: this.showShop.userId,
				})
				if (res.code == 200) {
					this.sucMes(this, "商家修改信息成功!")
					this.get()
				}
			})
		},
		submitShop(text, func) {
			this.prompt(
				{
					func: this.$prompt,
					text: `${text}:请输入店铺名称`,
					errMes: "店铺名称格式不正确",
				},
				UserUtil.verifyUsername,
				func
			)
		},

		async submitPassForm() {
			if (this.checkForm(this, "passForm")) {
				let passTo = {
					oldPassword: this.passForm.oldPass,
					newPassword: this.passForm.newPass,
				}
				let res = await updatePass(passTo)
				if (res.code == 200) {
					this.sucMes("用户修改密码成功!")
					this.get()
				}
			}
		},

		async submitBaseUserForm() {
			if (this.checkForm(this, "baseUserForm")) {
				let res = await updateUser(this.baseUserForm)
				if (res.code == 200) {
					this.sucMes("用户修改信息成功!")
					this.get()
				}
			}
		},
		beforeAvatarUpload({ raw: file }) {
			const isJPng = file.type === "image/jpeg" || "image/png"
			const isLt2M = file.size / 1024 < 800
			if (!isJPng) {
				this.$message.error("上传头像图片只能是 jpg/png 格式!")
				return
			}
			if (!isLt2M) {
				this.$message.error("上传头像图片大小不能超过 800kb!")
				return
			}
			this.cropper.avatar = URL.createObjectURL(file)
		},

		realTime(data) {
			this.previewStyle = {
				width: data.w + "px",
				height: data.h + "px",
				zoom: 1,
			}
			this.previews = data
		},
		rotateRight() {
			this.$refs.avatarCropper.rotateRight()
		},
		rotateLeft() {
			this.$refs.avatarCropper.rotateLeft()
		},
		updateScale(scale) {
			this.$refs.avatarCropper.updateScale(scale)
		},
		handlerObjConvertAry: TagCurMenu.handlerObjConvertAry,
		deleteTagAndUpdateCurMenu: TagCurMenu.deleteTagAndUpdateCurMenu,
	},
}
</script>

<style scoped>
.title {
	text-align: start;
	font-weight: bolder;
}
.avatar-box {
	position: relative;
	width: 130px;
	height: 130px;
	margin: 0 auto 20px;
}
.avatar {
	position: absolute;
	top: 0;
	left: 0;
}
.shape {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	border-radius: 50%;
	font-size: 60px;
	color: white;
	text-align: center;
	line-height: 130px;
	background: rgb(0, 0, 0, 0.3);
	opacity: 0;
}
.shape:hover {
	opacity: 1;
	cursor: pointer;
}
</style>
